import os

from const import K_LINES_ADDITIONAL

# from matplotlib.dates import DateFormatter, DayLocator
# from matplotlib.pylab import date2num
import matplotlib.pyplot as plt
# from matplotlib.finance import candlestick_ohlc
import matplotlib.ticker as mticker

from mpl_finance import candlestick_ohlc


def draw_detail_kchart(table_name, account_num, year, month, detail_list,
                       open_index, close_index, record_no):
    """画每笔交易的对应K线行情图，返回K线图 url.

    Args:

    Return:
        img_url (str): 返回生成K线图的url，方便入库
    """
    # plt.figure(figsize=(8, 6))
    fig, ax1 = plt.subplots(figsize=(10, 5))
    fig.subplots_adjust(bottom=0.4)
    ax1 = plt.subplot2grid((1, 1), (0, 0),
                           label=u"Price Chart of %s" % table_name)
    plt.subplots_adjust(left=None, bottom=None, right=None, top=None,
                        wspace=None, hspace=None)
    # fig, ax = plt.subplots(facecolor=(0.5, 0.5, 0.5))
    # fig.subplots_adjust(bottom=0.2)
    plt.style.use('seaborn-paper')
    start_delta = K_LINES_ADDITIONAL
    if open_index > start_delta:
        start = open_index - K_LINES_ADDITIONAL
    else:
        start = 0
        start_delta = open_index + 1
    end_delta = K_LINES_ADDITIONAL
    if close_index + K_LINES_ADDITIONAL < len(detail_list) - 1:
        end = close_index + K_LINES_ADDITIONAL
    else:
        end = len(detail_list) - 1
        end_delta = len(detail_list) - close_index - 1
    result = detail_list[start:end]
    ohlc = []
    highest = -1
    lowest = 999999
    for i in range(len(result)):
        append_me = []
        append_me.append(i - K_LINES_ADDITIONAL)
        append_me.append(result[i][2])
        append_me.append(result[i][3])
        append_me.append(result[i][4])
        append_me.append(result[i][5])
        append_me.append(result[i][6])
        ohlc.append(append_me)
        # print(append_me)
        if result[i][3] > highest:
            highest = result[i][3]
        if result[i][4] < lowest:
            lowest = result[i][4]
    # print(ohlc)
    # print(len(ohlc))
    ohlc[start_delta][2] = highest
    ohlc[start_delta][3] = lowest
    ohlc[len(result) - 1 - end_delta][2] = highest
    ohlc[len(result) - 1 - end_delta][3] = lowest
    candlestick_ohlc(ax1, ohlc, width=0.5, colorup='#ff0000',
                     colordown='#24ff24')
    # ax1.xaxis.set_ticklabels(xaxis_label)
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(20))
    plt.setp(plt.gca().get_xticklabels(), rotation=45)
    ax1.grid(True)
    plt.grid(True)
    plt.xlabel("Holding Cycles")
    plt.ylabel("Price")
    str_title = u"History Chart: %s" % table_name
    plt.title(str_title)
    plt.legend()
    basedir = os.path.abspath(os.path.dirname(__file__))
    imagefile_dir = os.path.join(basedir, './static/tmp_pic/')
    image_filename = "result_detail_%s_%s_%s_%s" % (account_num, year, month,
                                                    record_no)
    if os.path.exists(image_filename):
        os.remove(image_filename)
    imagefile_url = imagefile_dir + image_filename
    plt.savefig(imagefile_url)
    return image_filename

if __name__ == '__main__':
    import sqlite3
    conn = sqlite3.connect("data.sqlite")
    table_name = "I1705_60m"
    sql_str = ("SELECT * FROM %s" % table_name)
    account_num = "011002301945"
    year = "2017"
    month = "134"
    detail_list = conn.execute(sql_str).fetchall()
    # print(detail_list)
    draw_detail_kchart(table_name, account_num, year, month, detail_list,
                       100, 200, 1)

